<?php
/******************LENGTH******************/
function byteLength( $str ){
	return strlen( $str );//mb_strlen
}

function length(){
	return strlen($str);
}

/******************TYPE CHECK******************/
function isEmail( $email )
{
	return (bool) preg_match('/^[-_a-z0-9\'+*$^&%=~!?{}]++(?:\.[-_a-z0-9\'+*$^&%=~!?{}]+)*+@(?:(?![-.])[-a-z0-9.]+(?<![-.])\.[a-z]{2,6}|\d{1,3}(?:\.\d{1,3}){3})(?::\d++)?$/iD', (string) $email);
}

function isDate( $str )
{
	return ( strtotime($str) !== FALSE );
}

function soyia_area_format($area){
	return str_replace("^", "", $area);
}

function soyia_name_from_email( $email )
{
	$array_info = array();
	$array_info = explode('@', $email);
	return $array_info[0];
}

function soyia_name_regular($username, $nick_name, $first_name, $last_name)
{
	if($nick_name != '' )
	{
		return $nick_name;
	}
	
	if( $first_name != '' && $last_name != '') {
		return $first_name.' '.$last_name;
	}
	
	if($username != '' ){
		return soyia_name_from_email($username);
	}
	
	return 'Unamed';
}

function soyia_sql_date_add_hours($hours)
{
	return "date_add('".date("Y-m-d H:i:0")."', INTERVAL {$hours} HOUR)";
}

function soyia_string_random($num)
{
	$word = 'abcdefghijklmnopqrstuvwxyz0123456789';
	$len = strlen($word);
	$len = $len-2;
	$str = '';
	for ($x=0;$x<$num;$x++){
		$i = rand(0,$len);
		$theword = substr($word,$i,1);
		$str .= $theword;
	}
	return $str;
}

function isNumeric($str)
{
	//Use localeconv to set the decimal_point value: Usually a comma or period.
	$locale = localeconv();
	return (preg_match('/^[-0-9'.$locale['decimal_point'].']++$/D', (string) $str));
}

/******************PAGE HEADER******************/
function PageTitle($title, $show_sitename=false)
{
	if( $title == "" ){
		echo WEBSITE_NAME;
	} else {
		echo $title;
		
		if($show_sitename){
			echo '----'.WEBSITE_NAME;
		}
	}
}

/******************STRING FORMAT******************/
//Format String using Regex Patterns
function Format($str)
{
	$temp_str = $str;

	//count arguments that our function received
	$count_args=func_num_args();
	//check if we have sufficient arguments
	if($count_args==1){return $str;}

	//find all ocurrences that matches the pattern {(numbers)}
	//and copy them to an auxiliary array named $indexes
	//we'll use PREG_SET_ORDER so that we can get a pair of values
	//with all the matches found,
	//for example: array[y]=array([0]=>"{x}", [1]=>"x");
	preg_match_all('/\{(\d+)\}/', $temp_str, $indexes,PREG_SET_ORDER);

	$count=sizeof($indexes);

	//looping through our $indexes will give us
	//the elements to replace with
	for($i=0;$i<$count;$i++){
		$arr=$indexes[$i];

		//what will we replace, for example {x} (on which x=([0-9]+)
		$replace=$arr[0];
		//get argument value that will replace our {x}
		$arg_pos=$arr[1]+1;

		// check if we have a valid argument
		if($arg_pos>-1 && $arg_pos<$count_args){
			//get the argument value
			$arg_value=func_get_arg($arg_pos);
			//replace {x} with the value of specific argument position
			$temp_str = str_replace($replace,$arg_value, $temp_str);
		}
	}

	return $temp_str;

}

//Format String using only str_replace
function FormatSimpler($str)
{
	$temp_str = $str;

	//count arguments that our function received
	$count_args=func_num_args();
	//check if we have sufficient arguments
	if($count_args==1){return $str;}

	for($i=0;$i<$count_args-1;$i++){
		//get the argument value
		$arg_value=func_get_arg($i+1);
		//replace {$i} with the value of specific argument position
		$temp_str = str_replace("{{$i}}",$arg_value, $temp_str);
	}

	return $temp_str;
}

function IsServer()
{
	$IsServer = false;
	
	if(version_compare(PHP_VERSION, '5.3', '>=') ){
		//only for 5.3.0
		$host_info = strstr($_SERVER['HTTP_HOST'], '.', true);
	} else {
		//only for 5.2
		$host_info = strstr($_SERVER['HTTP_HOST'], '.');
		$host_info = str_replace($host_info, '', $_SERVER['HTTP_HOST']);
	}
	//var_dump($host_info);
	
	preg_match('/tzj/i', $host_info, $array_matches);
	//die(var_dump($array_matches));
	
	if(count($array_matches) <= 0) {
		$IsServer = true;
	}
	
	return $IsServer;
}

/******************File Name of Member******************/
function getMemberFolder($Member_id, $folder_name='')
{
	$folder = $Member_id>=1000?floor($Member_id/1000)*1000:ceil($Member_id/1000);
	
	return DIRECTORY_SEPARATOR."attachment".DIRECTORY_SEPARATOR.$folder.DIRECTORY_SEPARATOR.$Member_id.DIRECTORY_SEPARATOR.$folder_name;
}

//获取客户端IP地址，非法IP设为"unknow"。
function GetClientIp(){
	if($_SERVER['HTTP_X_FORWARDED_FOR']){
		$clientip = $_SERVER['HTTP_X_FORWARDED_FOR'];
	}elseif($_SERVER['HTTP_CLIENT_IP']){
		$clientip = $_SERVER['HTTP_CLIENT_IP'];
	}else{
		$clientip = $_SERVER['REMOTE_ADDR'];
	}
	//echo $clientip;
	$clientip = preg_match("/^([0-9]{1,3}\.){3}[0-9]{1,3}$/", $clientip) ? $clientip : 'unknown';
	return $clientip;
}


//从字符串中截取指定长度的子串，支持中文，不支持utf8
function SubStrs($content,$length,$t=0){
	//t=0 截取字节 t=1截取个数
	if($length && strlen($content)>$length){
		$retstr='';
		for($i = 0; $i < $length-2; $i++) {
			if(ord($content[$i]) > 127){
				if($t){
					$retstr .=$content[$i].$content[$i+1];
					$i++;
					$length++;
				}else{
					if(($i+1<$length-2)){
						$retstr .=$content[$i].$content[$i+1];
						$i++;
					}
				}
			}else{
				$retstr .=$content[$i];
			}
		}
		return $retstr.'..';
	}
	return $content;
}

//返回指定长度的数字串
function NumRand($lenth){
	mt_srand((double)microtime() * 1000000);
	for($i=0;$i<$lenth;$i++){
		$randval.= mt_rand(0,9);
	}
	return $randval;
}

/**
 * 抛出一个致命的程序错误
 *
 * @param string $msg
 */
function ThrowError($msg){
	$errmsg="<div style='font-size:12px;font-family:verdana;line-height:180%;color:#000;border:dashed 1px #ccc;padding:10px;margin:20px;'>";
	$errmsg.="<span style='color:red;font-weight:bold'>Error: </span>";
	$errmsg.=$msg;
	$errmsg.="</div>";
	die($errmsg);
}

function gotopage($url)
{
	header('Location: '.$url);
	die();
}

function htmlSuccess( $msg, $url='', $redirectSeconds=0)
{
	htmlMessage( $msg, $url, $redirectSeconds, "1" );
}

function htmlError( $msg, $url='', $redirectSeconds=0 )
{
	htmlMessage( $msg, $url, $redirectSeconds, "2" );
}
function htmlMessage( $msg, $url, $redirectSeconds, $type )
{
	$tip = __("Error");
	switch($type)
	{
		case "1":
			$tip = __("Success");
	}
	$append_message = "";
	$message .= '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>';
if( $redirectSeconds != 0 && $url != ''){
	$message .= '<META HTTP-EQUIV="Refresh" CONTENT="'.$redirectSeconds.'; URL='.$url.'">';
	$append_message .= '<br />'.__("Page will be changed in $redirectSeconds seconds automaticly.");
}
$message .= '</head>
<body>';
	$message .= '<div style="width:60%; margin:120px auto;font-size:14px; font-family:verdana; line-height:180%; color:#000; border:dashed 1px #ccc; padding:10px;">';
	$message .= "<span style='color:red;font-weight:bold'>".$tip.": </span>".$msg.$append_message;
	if( $url != "" ){
		$message .= '<div style="float:left; clear:left; width: 100%; text-align: center;"><a href="'.$url.'" >Okay</a></div>';
	} else {
		$message .= '<div style="float:left; clear:left; width: 100%; text-align: center;"><a href="#" onclick="window.history.back(-1);return false;">back</a></div>';
	}
	$message .= "</div>";
	die($message);
}

$month_array = array("01" => 'Jan', "02" =>'Feb', "03" => 'Mar' , "04" => 'Apr' , "05" => 'May' , "06" => 'June' , "07" => 'July' , "08" => 'Aug' , "09" => 'Sept' , "10" => 'Oct' , "11" => 'Nov' , "12" => 'Dec');

//记录日志函数
function LogFile($log_file, $operation, $message, $time="")
{
	$fp = fopen($log_file, "a");
	if($time=="")
	{
		$time = date("Y-m-d H:i:s D");
	}
	@fwrite($fp,$time." [$operation] : $message\n");
	@fclose($fp);
}

function utf8_strlen($str) {
	$count = 0;
	for($i = 0; $i < strlen($str); $i++){
		$value = ord($str[$i]);
		if($value > 127) {
			$count++;
			if($value >= 192 && $value <= 223) $i++;
			elseif($value >= 224 && $value <= 239) $i = $i + 2;
			elseif($value >= 240 && $value <= 247) $i = $i + 3;
			else die('Not a UTF-8 compatible string');
		}
		$count++;
	}
	return $count;
}


//截取字符串-UTF8(PHP)
function utf8_substr($str,$position,$length){

	$start_position = strlen($str);
	$start_byte = 0;
	$end_position = strlen($str);
	$count = 0;
	for($i = 0; $i < strlen($str); $i++){
		if($count >= $position && $start_position > $i){
			$start_position = $i;
			$start_byte = $count;
		}
		if(($count-$start_byte)>=$length) {
			$end_position = $i;
			break;
		}
		$value = ord($str[$i]);
		if($value > 127){
			$count++;
			if($value >= 192 && $value <= 223) $i++;
			elseif($value >= 224 && $value <= 239) $i = $i + 2;
			elseif($value >= 240 && $value <= 247) $i = $i + 3;
			else die('Not a UTF-8 compatible string');
		}
		$count++;

	}
	return(substr($str,$start_position,$end_position-$start_position));
}

//取出特定长度的字符串，并以一定字符结尾
function substr_utf8($str, $length, $length_more=3, $plus_text='...', $position=0)
{
	$start_position = strlen($str);
	$start_byte = 0;
	$end_position = strlen($str);
	$end_position_changed = false;
	$end_position_template = 0;
	$count = 0;
	for($i = 0; $i < strlen($str); $i++){
		if($count >= $position && $start_position > $i){
			$start_position = $i;
			$start_byte = $count;
		}
		$temp = $count-$start_byte;
	//	die(var_dump($temp).$i.']<br />');
		//die('a');
		if(($count-$start_byte) >= $length) {
			$end_position_template = $i;
			break;
		}
		if(($count-$start_byte)>=$length-$length_more && $end_position_changed == false) {
			$end_position = $i;
			$end_position_changed = true;
			//break;
		}
		$value = ord($str[$i]);
		if($value > 127){
			$count++;
			if($value >= 192 && $value <= 223) $i++;
			elseif($value >= 224 && $value <= 239) $i = $i + 2;
			elseif($value >= 240 && $value <= 247) $i = $i + 3;
			else 
			{
				echo '<script> alert("'.$this->language->_r("Not a UTF-8 compatible string").'"); history.back();</script>';
				exit();
			}
		}
		$count++;
	}
	//die(var_dump($end_position_template).']');
	if( $end_position_template == 0 || $end_position_template == strlen($str) ){
		//die(var_dump(strlen($str)).']]]');
		if( $end_position_template != 0){
			$end_position = $end_position_template;
		} else {
			$end_position = strlen($str);
		}
		//die(var_dump($end_position).']');
		$plus_text = "";
	} else {
	//die("bbb");
	}
	//die(var_dump($plus_text));
	return(substr($str, $start_position, $end_position-$start_position).$plus_text);
}

function WriteBorder($type, $width_now)
{
	if( $width_now == ""){
		$width_now = 306;
	}

	if( $type == 1){
		echo '<ul style="float:left; clear:left; width:'.$width_now.'px; height:auto;">
					<li style="float:left; clear:left; width:'.$width_now.'px; height:2px; font-size:0px; background-image: url(\'/images/y_2_2.jpg\'); background-position:left top; background-repeat: repeat-x;">
						<span style="float:left; clear:left; width:2px; height:2px; font-size:0px; background-image: url(\'/images/y_2_1.jpg\'); background-position:left top; background-repeat: no-repeat;"></span>
						<span style="float:right; clear:right; width:2px; height:2px; font-size:0px; background-image: url(\'/images/y_2_1.jpg\'); background-position:right top; background-repeat: no-repeat;"></span>
					</li>
					<li style="float:left; clear:left; height:auto; width:'.($width_now-2).'px; overflow-x:hidden; border-left:solid 1px #cbddef;  border-right:solid 1px #cbddef;">';
	}else{
		echo '	</li>
					<li style="float:left; clear:left; width:'.$width_now.'px; height:2px; font-size:0px; background-image: url(\'/images/y_2_2.jpg\'); background-position:left bottom; background-repeat: repeat-x;">
						<span style="float:left; clear:left; width:2px; height:2px; font-size:0px; background-image: url(\'/images/y_2_1.jpg\'); background-position:left bottom; background-repeat: no-repeat;"></span>
						<span style="float:right; clear:right; width:2px; height:2px; font-size:0px; background-image: url(\'/images/y_2_1.jpg\'); background-position:right bottom; background-repeat: no-repeat;"></span>
					</li>
				</ul>';
	}
}

function createXML($name, &$objs)
{
	if(count($objs) > 0 ){
		$reflector = new ReflectionObject($objs[0]);
		$array_property = $reflector->getProperties();

		$iCount = count($array_property);
	}

	$dom = new DomDocument();
	$dom->formatOutput = true;
	$root = $dom->createElement( $name );
	$dom->appendChild( $root );

	foreach($objs as $obj)
	{

		$dom_Multilingual = $dom->createElement( $name );

		$root->appendChild( $dom_Multilingual );

		for($i=0; $i<$iCount; $i++){
			$field_name = $array_property[$i]->name;
			$column = $dom->createElement( $field_name );
			$column->appendChild( $dom->createTextNode( $obj->$field_name) );
			$dom_Multilingual->appendChild( $column );
		}
	}

	header( "Content-type: text/xml" );
	echo $dom->saveXML();
}

function StringToArray( $StringsOrArray, $Separator=",")
{
	if( !is_array($StringsOrArray))
	{
		if( $StringsOrArray == ""){
			$StringsOrArray = array();
		} else {
			$StringsOrArray = explode($Separator, $StringsOrArray);
		}
	}
	
	return $StringsOrArray;
}

function formattime($time){
	$array_time = explode(':', $time);
	
	return $array_time[0].':'.$array_time[1];
}
?>